package ua.kpi.oblamskyiv.io;

import ua.kpi.oblamskyiv.io.exception.IllegalAnswerFormatException;
import ua.kpi.oblamskyiv.io.exception.IllegalAnswerIndexException;
import ua.kpi.oblamskyiv.io.exception.IllegalAnswersNumberException;
import ua.kpi.oblamskyiv.testcase.Answers;
import ua.kpi.oblamskyiv.testcase.question.Question;

import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintStream;
import java.util.Scanner;

/**
 * Tester input/output class. Manages input/output operations
 * for questions, stats and answers via InputStream and OutputStream
 */
public class TesterIO {
    private PrintStream printStream;
    private Scanner scanner;

    public TesterIO(InputStream in, OutputStream out) {
        scanner = new Scanner(in);
        printStream = new PrintStream(out);
    }

    public void outQuestion(Question question) {
        printStream.print(question);
    }

    public void outResult(double score) {
        printStream.format("Your score: %.2f points\n\n", score);
    }

    /**
     * Getting list of answers from user
     *
     * @param question question to get answer on
     * @return list of user answers
     */
    public Answers getUserAnswers(Question question) {
        while (true) {
            printStream.print("Answer: ");
            String stringAnswer = scanner.nextLine();

            try {
                return question.getAnswersFromString(stringAnswer);
            } catch (IllegalAnswersNumberException e) {
                printStream.println("Invalid answers number!");
            } catch (IllegalAnswerIndexException e) {
                printStream.println("Invalid answer index!");
            } catch (IllegalAnswerFormatException e) {
                printStream.println("Invalid input!");
            }
        }
    }
}
